<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#f76c5d" />
    <meta name="description" content="ArozOS Photo" />
    <link rel="manifest" crossorigin="use-credentials" href="manifest.json">
    <title>Photo</title>
    <link rel="stylesheet" href="../script/semantic/semantic.min.css">
    <script src="../script/alpine.min.js"></script>
    <script src="../script/jquery.min.js"></script>
    <script src="../script/semantic/semantic.min.js"></script>
    <script src="../script/ao_module.js"></script>
    <script src="constants.js"></script>
    <script src="histogram.js"></script>
    <script src="photo.js"></script>
    <style>
        #main {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        
        #menu {
            flex: 0 0 auto;
            width: 100%;
            height: auto;
        }
        
        #path-selector {
            flex: 0 0 auto;
            padding: 1em;
            background: #2c2c2c;
            border-bottom: 1px solid #444;
            color: #ffffff;
        }
        
        #display {
            flex: 1;
            margin: 0;
            overflow: hidden;
            background: #1a1a1a;
        }
        
        body {
            overflow: hidden;
            background: #1a1a1a;
            color: #ffffff;
        }

        .imagecard{
            border: 1px solid #444;
            overflow: hidden;
        }

        .imagecard img{
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center;
        }

        #viewbox{
            margin-left: 0px !important;
            margin-top: 0px !important;
            position: relative;
           
        }

        #viewboxContainer{
            height: 100%;
            overflow-y: auto;
            overflow-x: hidden;
        }

        #fadeplate{
            position: absolute;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 100%;
            background: rgba(20,20,20,0.8);
            backdrop-filter: blur(2px);
        }

        .subfolders-container {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5em;
        }

        #noimg {
            text-align: center;
            margin: 2em auto;
            max-width: 400px;
            color: white;
        }

        #noimg .sub.header {
            color: #cccccc;
        }

        .photo-viewer {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.95);
            z-index: 1000;
            display: none;
        }

        .viewer-content {
            display: flex;
            height: 100%;
            position: relative;
        }

        .viewer-bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
        }

        .viewer-bg img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            filter: blur(20px);
        }

        .viewer-left, .viewer-right {
            z-index: 2;
            position: relative;
        }

        .viewer-left {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            overflow: hidden;
            cursor: grab;
        }

        .viewer-left img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            transition: transform 0.1s ease-out;
            cursor: auto;
            user-select: none;
        }

        .viewer-left img.zoomed {
            max-width: none;
            max-height: none;
            cursor: grab;
        }

        .viewer-left img.dragging {
            cursor: grabbing;
        }

        .viewer-right {
            width: 350px;
            background: rgba(40, 40, 40,0.6);
            padding: 20px;
            color: white;
            overflow-y: auto;
        }

        .info-panel h3 {
            margin-top: 0;
            color: #f76c5d;
        }

        .info-panel h4 {
            margin-top: 20px;
            margin-bottom: 10px;
            color: #f76c5d;
        }

        .info-panel h5 {
            margin-top: 15px;
            margin-bottom: 5px;
            color: #cccccc;
            font-size: 0.9em;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .info-panel table {
            width: 100%;
            margin-bottom: 10px;
        }

        .info-panel .exif-section-table {
            margin-bottom: 15px;
        }

        .info-panel td {
            word-wrap: break-word;
            overflow-wrap: break-word;
            hyphens: auto;
            padding: 6px 4px;
            font-size: 0.9em;
        }

        .info-panel td:first-child {
            font-weight: bold;
            width: 120px;
            white-space: nowrap;
            color: #cccccc;
        }

        .info-panel td:last-child {
            word-break: break-all;
        }

        .close-btn {
            position: absolute;
            top: 1em;
            right: 1em;
            background: #222222;
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            line-height: 1;
            z-index: 500;
        }

        .close-btn.info-panel-close {
            display: none;
        }

        #shooting-params-section .column {
            padding: 0.1em !important;
        }

        #shooting-params-section .propertiesLabel {
             border: 1px solid #c0c0c0 !important;
             border-radius: 0.4em !important;
             margin: 0.1em;
             padding: 0.2em 0.4em;
        }

        #shooting-params-grid{
            margin: 0 !important;
        }

        .show-info-btn {
            position: absolute;
            top: 1em;
            right: 3em;
            background: #222222;
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 18px;
            line-height: 1;
            z-index: 500;
            display:none;
        }

        @media (max-width: 768px) {
            .viewer-right {
                position: fixed;
                right: 0;
                backdrop-filter: blur(10px);
                height: 100%;
                overflow-y: auto;
                background-color: rgba(40, 40, 40,0.8);
                display:none;
            }
            .close-btn {
                position: fixed;
                right: 1em;
            }
            .close-btn.info-panel-close {
                display: block;
            }

            .show-info-btn {
                display: block;
            }
        }

        /* Zoom Snackbar Styles */
        .zoom-snackbar {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            font-family: Arial, sans-serif;
            z-index: 1001;
            backdrop-filter: blur(4px);
        }

        .zoom-reset-btn {
            background: #f76c5d;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.2s;
        }

        .zoom-reset-btn:hover {
            background: #e55a4f;
        }

        @media (max-width: 768px) {
            .zoom-snackbar {
                display: none !important;
            }
        }
    </style>

</head>
<body>
    <div id="main" x-data='photoListObject()' x-init="init()">
        <div class="ui inverted secondary small menu" id="menu">
            <div class="item">
                <img class="ui fluid image" src="img/banner.png" style="max-height: 40px;">
            </div>
            <div class="ui inverted dropdown item">
                Disk <i class="dropdown icon"></i>
                <div class="menu">
                    <template x-for="vroot in vroots">
                        <a class="item" :rootpath="vroot[1]" x-on:click="updateRenderingPath(vroot[2]);"><i class="ui disk icon"></i> <span x-text="vroot[0] + ' (' + vroot[1] + ')'"></span></a>
                    </template>
                    
                </div>
            </div>
            <div class="ui inverted dropdown item">
                Sort By <i class="dropdown icon"></i>
                <div class="menu">
                    <a class="item" x-on:click="changeSort('default');" :class="{ 'active': sortOrder === 'default' }"><i class="ui sort alphabet up icon"></i> Filename Ascending</a>
                    <a class="item" x-on:click="changeSort('reverse');" :class="{ 'active': sortOrder === 'reverse' }"><i class="ui sort alphabet down icon"></i> Filename Descending</a>
                    <a class="item" x-on:click="changeSort('smallToLarge');" :class="{ 'active': sortOrder === 'smallToLarge' }"><i class="ui sort amount up icon"></i> Size Small to Large</a>
                    <a class="item" x-on:click="changeSort('largeToSmall');" :class="{ 'active': sortOrder === 'largeToSmall' }"><i class="ui sort amount down icon"></i> Size Large to Small</a>
                    <a class="item" x-on:click="changeSort('mostRecent');" :class="{ 'active': sortOrder === 'mostRecent' }"><i class="ui calendar icon"></i> Newest First</a>
                    <a class="item" x-on:click="changeSort('leastRecent');" :class="{ 'active': sortOrder === 'leastRecent' }"><i class="ui calendar outline icon"></i> Oldest First</a>
                    <a class="item" x-on:click="changeSort('fileTypeAsce');" :class="{ 'active': sortOrder === 'fileTypeAsce' }"><i class="ui file alternate icon"></i> Extension Ascending</a>
                    <a class="item" x-on:click="changeSort('fileTypeDesc');" :class="{ 'active': sortOrder === 'fileTypeDesc' }"><i class="ui file alternate outline icon"></i> Extension Descending</a>
                    <a class="item" x-on:click="changeSort('smart');" :class="{ 'active': sortOrder === 'smart' }"><i class="ui magic icon"></i> Natural Order</a>
                </div>
            </div>
            
            <!-- Right floated menu -->
            <a class="right floated icon item" x-on:click="toggleViewMode();">
                <i x-show="viewMode === 'grid'" class="ui bars large icon"></i>
                <i x-show="viewMode === 'list'" class="ui th large icon"></i>
            </a>

        </div>

        <div id="path-selector">
            <div class="ui inverted breadcrumb">
                <span x-text="currentPath"></span>
            </div>
            <div class="ui divider"></div>
            <div >
                <a id="parentFolderButton" class="ui basic inverted button" x-on:click="parentFolder();" style="display:none; margin-top: 0.6em;">
                    <i class="reply icon"></i> Parent Folder
                </a>
                <div id="subfolders-buttons" class="subfolders-container" style="margin-top: 0.6em;">
                    <div class="item" id="nosubfolder" style="display:none;"><!-- <i class="ui green circle check icon"></i> No Sub Folders --></div>
                    <template x-for="folder in folders">
                        <a class="ui basic small inverted button" x-on:click="updateRenderingPath(folder);"><i class="ui folder open icon"></i> <span x-text="extractFolderName(folder);"></span></a>
                    </template>
                </div>
            </div>
        </div>

        <div id="display">
            <div id="noimg" class="ui basic inverted segment" style="display:none;">
                <h4 class="ui header">
                    <div class="content">
                        Empty Folder
                        <div class="sub header">There are no photo stored in <span x-text="currentPath + '/'"></span></div>
                    </div>
                </h4>
            </div>
            <div id="viewboxContainer">
                <div x-show="viewMode === 'grid'" id="viewbox" class="ui six cards viewbox">
                    <template x-for="image in images">
                        <div class="imagecard" style="cursor: pointer;" x-on:click="showImage($el); ShowModal();" :style="{width: renderSize + 'px', height: renderSize + 'px'}" :filedata="encodeURIComponent(JSON.stringify({'filename':image.split('/').pop(),'filepath':image}))">
                            <a class="image" x-init="updateImageSizes();">
                                <img :src="'../system/file_system/loadThumbnail?bytes=true&vpath=' + image">
                            </a>
                        </div>
                    </template>
                </div>
                <div x-show="viewMode === 'list'" class="ui relaxed divided inverted list">
                    <template x-for="image in images">
                        <div class="item" style="cursor: pointer; padding-left: 10px; " x-on:click="showImage($el); ShowModal();" :filedata="encodeURIComponent(JSON.stringify({'filename':image.split('/').pop(),'filepath':image}))">
                            <img class="ui small image" :src="'../system/file_system/loadThumbnail?bytes=true&vpath=' + image"
                                 style="width: 60px; height: 60px;">
                            <div class="content">
                                <div class="header" x-text="image.split('/').pop()"></div>
                                <div class="description" x-text="image"></div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        
    </div>
    <!-- Photo Viewer -->
    <div id="photo-viewer" class="photo-viewer">
        
        <div class="viewer-content">
            <div class="viewer-bg">
                <img id="bg-image" src="" />
            </div>
            <div class="viewer-left">
                <img id="fullImage" src="img/loading.png" />
                <button class="close-btn" onclick="closeViewer()">×</button>
                <button class="show-info-btn" onclick="showInfoPanel()">ℹ</button>
            </div>
            <div class="viewer-right">
                <div>
                    <button class="close-btn info-panel-close" onclick="hideInfoPanel()">×</button>
                </div>
                <div class="info-panel">
                    <h3>Photo Information</h3>
                    <table class="ui very basic compact table inverted">
                        <tbody>
                            <tr>
                                <td><strong>Filename:</strong></td>
                                <td><span id="info-filename"></span></td>
                            </tr>
                            <tr>
                                <td><strong>Filepath:</strong></td>
                                <td><span id="info-filepath"></span></td>
                            </tr>
                            <tr>
                                <td><strong>Image Dimensions:</strong></td>
                                <td><span id="info-dimensions">Loading...</span></td>
                            </tr>
                        </tbody>
                    </table>
                    <h4>EXIF Data</h4>
                    <div id="exif-data">
                        <!-- Basic Information -->
                        <div id="basic-info-section" style="display: none;">
                            <h5>Basic Information</h5>
                            <table class="ui very basic compact table inverted exif-section-table">
                                <tbody>
                                    <tr id="format-row" style="display: none;"><td>Format</td><td id="format-value"></td></tr>
                                    <tr id="dimensions-row" style="display: none;"><td>Dimensions</td><td id="dimensions-value"></td></tr>
                                    <tr id="pixels-row" style="display: none;"><td>Pixels</td><td id="pixels-value"></td></tr>
                                    <tr id="color-space-row" style="display: none;"><td>Color Space</td><td id="color-space-value"></td></tr>
                                    <tr id="shooting-time-row" style="display: none;"><td>Shooting Time</td><td id="shooting-time-value"></td></tr>
                                    <tr id="software-row" style="display: none;"><td>Software</td><td id="software-value"></td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="ui divider" id="basic-info-divider" style="display: none;"></div>

                        <!-- Shooting Parameters -->
                        <div id="shooting-params-section" style="display: none;">
                            <h5>Shooting Parameters</h5>
                            <div id="shooting-params-grid" class="ui grid">
                                <div class="eight wide column" id="focal-length-row" style="display: none;">
                                    <div class="propertiesLabel">
                                        <img src="img/focal.svg" alt="Focal Length Icon" style="width: 16px; height: 16px; margin-right: 5px; margin-bottom: -0.2em">
                                        <span id="focal-length-value"></span>
                                    </div>
                                </div>
                                <div class="eight wide column" id="aperture-row" style="display: none;">
                                    <div class="propertiesLabel">
                                        <img src="img/aperature.svg" alt="Focal Length Icon" style="width: 16px; height: 16px; margin-right: 5px; margin-bottom: -0.2em">
                                        <span id="aperture-value"></span>
                                    </div>
                                </div>
                                <div class="eight wide column" id="shutter-speed-row" style="display: none;">
                                    <div class="propertiesLabel">
                                        <img src="img/shutter_speed.svg" alt="Focal Length Icon" style="width: 16px; height: 16px; margin-right: 5px; margin-bottom: -0.2em">
                                        <span id="shutter-speed-value"></span>
                                    </div>
                                </div>
                                <div class="eight wide column" id="iso-row" style="display: none;">
                                    <div class="propertiesLabel">
                                        <img src="img/iso.svg" alt="Focal Length Icon" style="width: 16px; height: 16px; margin-right: 5px; margin-bottom: -0.2em">
                                        <span>ISO </span><span id="iso-value"></span>
                                   </div>
                                </div>
                                <div class="eight wide column" id="ev-row" style="display: none;">
                                    <div class="propertiesLabel">
                                        <img src="img/exposure.svg" alt="EV Icon" style="width: 16px; height: 16px; margin-right: 5px; margin-bottom: -0.25em">
                                        <span>EV </span> <span id="ev-value"></span>
                                    </div>  
                                </div>  
                            </div>
                        </div>
                        <div class="ui divider" id="shooting-params-divider" style="display: none;"></div>

                        <!-- Tone Analysis -->
                        <div id="tone-analysis-section" style="display: none;">
                            <h5>Tone Analysis</h5>
                            <table class="ui very basic compact table inverted exif-section-table">
                                <tbody>
                                    <tr><td>Tone Type</td><td class="tone-type-value">Analyzing...</td></tr>
                                    <tr><td>Brightness</td><td class="brightness-value">Analyzing...</td></tr>
                                    <tr><td>Contrast</td><td class="contrast-value">Analyzing...</td></tr>
                                    <tr><td>Shadow Ratio</td><td class="shadow-ratio-value">Analyzing...</td></tr>
                                    <tr><td>Highlight Ratio</td><td class="highlight-ratio-value">Analyzing...</td></tr>
                                    <tr><td colspan="2"><canvas id="histogram-canvas" width="300" height="120" style="width: 100%; height: 120px; background: #222; margin: 10px 0; border-radius: 4px;"></canvas></td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="ui divider" id="tone-analysis-divider" style="display: none;"></div>

                        <!-- Device Information -->
                        <div id="device-info-section" style="display: none;">
                            <h5>Device Information</h5>
                            <table class="ui very basic compact table inverted exif-section-table">
                                <tbody>
                                    <tr id="camera-row" style="display: none;"><td>Camera</td><td id="camera-value"></td></tr>
                                    <tr id="lens-row" style="display: none;"><td>Lens</td><td id="lens-value"></td></tr>
                                    <tr id="focal-length-device-row" style="display: none;"><td>Focal Length</td><td id="focal-length-device-value"></td></tr>
                                    <tr id="max-aperture-row" style="display: none;"><td>Max Aperture</td><td id="max-aperture-value"></td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="ui divider" id="device-info-divider" style="display: none;"></div>

                        <!-- Shooting Mode -->
                        <div id="shooting-mode-section" style="display: none;">
                            <h5>Shooting Mode</h5>
                            <table class="ui very basic compact table inverted exif-section-table">
                                <tbody>
                                    <tr id="exposure-program-row" style="display: none;"><td>Exposure Program</td><td id="exposure-program-value"></td></tr>
                                    <tr id="exposure-mode-row" style="display: none;"><td>Exposure Mode</td><td id="exposure-mode-value"></td></tr>
                                    <tr id="metering-mode-row" style="display: none;"><td>Metering Mode</td><td id="metering-mode-value"></td></tr>
                                    <tr id="white-balance-row" style="display: none;"><td>White Balance</td><td id="white-balance-value"></td></tr>
                                    <tr id="flash-row" style="display: none;"><td>Flash</td><td id="flash-value"></td></tr>
                                    <tr id="scene-capture-row" style="display: none;"><td>Scene Capture Type</td><td id="scene-capture-value"></td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="ui divider" id="shooting-mode-divider" style="display: none;"></div>

                        <!-- Technical Parameters -->
                        <div id="technical-params-section" style="display: none;">
                            <h5>Technical Parameters</h5>
                            <table class="ui very basic compact table inverted exif-section-table">
                                <tbody>
                                    <tr id="shutter-speed-tech-row" style="display: none;"><td>Shutter Speed</td><td id="shutter-speed-tech-value"></td></tr>
                                    <tr id="aperture-value-row" style="display: none;"><td>Aperture Value</td><td id="aperture-value-value"></td></tr>
                                    <tr id="focal-plane-res-row" style="display: none;"><td>Focal Plane Resolution</td><td id="focal-plane-res-value"></td></tr>
                                </tbody>
                            </table>
                        </div>

                        <!-- No EXIF data message -->
                        <div id="no-exif-message" style="display: none;">
                            <p>No EXIF data available</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Zoom Snackbar -->
        <div id="zoom-snackbar" class="zoom-snackbar" style="display: none;">
            <span id="zoom-level-display">x1.0</span>
            <button id="zoom-reset-btn" class="zoom-reset-btn" onclick="resetZoom()">Reset</button>
        </div>
    </div>

</body>
<script>

    //Calculate image size on document ready
    $(window).on("resize ", function() {
        updateImageSizes();
        
        // Show info panel when resizing to desktop width (> 768px)
        if (window.innerWidth > 768) {
            const infoPanel = document.querySelector('.viewer-right');
            if (infoPanel && infoPanel.style.display === 'none') {
                showInfoPanel();
            }
        }
    });

    function hideInfoPanel() {
        document.querySelector('.viewer-right').style.display = 'none';
    }

    function showInfoPanel() {
        document.querySelector('.viewer-right').style.display = 'block';
    }

    // Zoom and Pan functionality
    let zoomLevel = 1;
    let panX = 0;
    let panY = 0;
    let isDragging = false;
    let lastMouseX = 0;
    let lastMouseY = 0;
    let initialDistance = 0;
    let initialZoom = 1;

    function resetZoom() {
        zoomLevel = 1;
        panX = 0;
        panY = 0;
        updateImageTransform();
        document.getElementById('fullImage').classList.remove('zoomed');
    }

    function updateImageTransform() {
        const img = document.getElementById('fullImage');
        const snackbar = document.getElementById('zoom-snackbar');
        const zoomDisplay = document.getElementById('zoom-level-display');
        
        if (zoomLevel > 1) {
            img.style.transform = `scale(${zoomLevel}) translate(${panX}px, ${panY}px)`;
            img.classList.add('zoomed');
            
            // Show zoom snackbar
            zoomDisplay.textContent = 'x' + zoomLevel.toFixed(1);
            snackbar.style.display = 'flex';
        } else {
            img.style.transform = 'none';
            img.classList.remove('zoomed');
            panX = 0;
            panY = 0;
            
            // Hide zoom snackbar
            snackbar.style.display = 'none';
        }
    }

    function zoomAtPoint(scale, centerX, centerY) {
        const img = document.getElementById('fullImage');
        const rect = img.getBoundingClientRect();
        const containerRect = img.parentElement.getBoundingClientRect();
        
        // Calculate the point relative to the image center
        const x = (centerX - rect.left) / rect.width - 0.5;
        const y = (centerY - rect.top) / rect.height - 0.5;
        
        // Calculate the zoom factor
        const newZoom = Math.max(1, Math.min(5, scale));
        
        if (newZoom !== zoomLevel) {
            // Adjust pan to keep the zoom point fixed
            const zoomFactor = newZoom / zoomLevel;
            panX = panX * zoomFactor - x * (newZoom - 1) * 50;
            panY = panY * zoomFactor - y * (newZoom - 1) * 50;
            
            zoomLevel = newZoom;
            constrainPan();
            updateImageTransform();
        }
    }

    function constrainPan() {
        const img = document.getElementById('fullImage');
        const rect = img.getBoundingClientRect();
        const containerRect = img.parentElement.getBoundingClientRect();
        
        const maxPanX = Math.max(0, (rect.width * zoomLevel - containerRect.width) / 2 / zoomLevel * 100);
        const maxPanY = Math.max(0, (rect.height * zoomLevel - containerRect.height) / 2 / zoomLevel * 100);
        
        panX = Math.max(-maxPanX, Math.min(maxPanX, panX));
        panY = Math.max(-maxPanY, Math.min(maxPanY, panY));
    }

    // Initialize zoom and pan when photo viewer is shown
    function initZoomPan() {
        const img = document.getElementById('fullImage');
        const container = document.querySelector('.viewer-left');
        
        // Reset zoom state
        resetZoom();

        // Define handler functions to allow removal and re-addition
        let handleDblClick = function(e) {
            console.log(e);
            e.preventDefault();
            if (zoomLevel > 1) {
                resetZoom();
            } else {
                zoomAtPoint(2, e.clientX, e.clientY);
            }
        };

        let handleWheel = function(e) {
            e.preventDefault();
            const delta = e.deltaY > 0 ? 0.9 : 1.1;
            let actualZoomLevel = zoomLevel * delta;
            if (actualZoomLevel < 1) actualZoomLevel = 1;
            if (actualZoomLevel > 3.3) actualZoomLevel = 3.3;
            zoomAtPoint(actualZoomLevel, e.clientX, e.clientY);
        };

        let handleMouseDown = function(e) {
            if (zoomLevel > 1) {
                e.preventDefault();
                isDragging = true;
                lastMouseX = e.clientX;
                lastMouseY = e.clientY;
                img.classList.add('dragging');
            }
        };

        let handleMouseMove = function(e) {
            if (isDragging && zoomLevel > 1) {
                const deltaX = e.clientX - lastMouseX;
                const deltaY = e.clientY - lastMouseY;
                
                panX += deltaX / zoomLevel;
                panY += deltaY / zoomLevel;
                
                constrainPan();
                updateImageTransform();
                
                lastMouseX = e.clientX;
                lastMouseY = e.clientY;
            }
        };

        let handleMouseUp = function() {
            if (isDragging) {
                isDragging = false;
                img.classList.remove('dragging');
            }
        };

        let handleTouchStart = function(e) {
            if (e.touches.length === 1) {
                // Single touch - prepare for pan
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
                if (zoomLevel > 1) {
                    isDragging = true;
                    img.classList.add('dragging');
                }
            } else if (e.touches.length === 2) {
                // Two touches - prepare for pinch zoom
                e.preventDefault();
                const touch1 = e.touches[0];
                const touch2 = e.touches[1];
                touchStartDistance = Math.sqrt(
                    Math.pow(touch2.clientX - touch1.clientX, 2) + 
                    Math.pow(touch2.clientY - touch1.clientY, 2)
                );
                initialZoom = zoomLevel;
                isDragging = false;
            }
        };

        let handleTouchMove = function(e) {
            e.preventDefault();
            
            if (e.touches.length === 1 && isDragging && zoomLevel > 1) {
                // Single touch pan
                const deltaX = e.touches[0].clientX - touchStartX;
                const deltaY = e.touches[0].clientY - touchStartY;
                
                panX += deltaX / zoomLevel;
                panY += deltaY / zoomLevel;
                
                constrainPan();
                updateImageTransform();
                
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
            } else if (e.touches.length === 2) {
                // Two touches pinch zoom
                const touch1 = e.touches[0];
                const touch2 = e.touches[1];
                const currentDistance = Math.sqrt(
                    Math.pow(touch2.clientX - touch1.clientX, 2) + 
                    Math.pow(touch2.clientY - touch1.clientY, 2)
                );
                
                if (touchStartDistance > 0) {
                    const scale = currentDistance / touchStartDistance;
                    const newZoom = Math.max(1, Math.min(5, initialZoom * scale));
                    
                    if (newZoom !== zoomLevel) {
                        // Zoom at center point between touches
                        const centerX = (touch1.clientX + touch2.clientX) / 2;
                        const centerY = (touch1.clientY + touch2.clientY) / 2;
                        zoomAtPoint(newZoom, centerX, centerY);
                    }
                }
            }
        };

        let handleTouchEnd = function(e) {
            if (e.touches.length === 0) {
                isDragging = false;
                img.classList.remove('dragging');
            }
        };

        // Remove existing listeners to prevent double triggering
        img.removeEventListener('dblclick', handleDblClick);
        img.removeEventListener('wheel', handleWheel);
        img.removeEventListener('mousedown', handleMouseDown);
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
        img.removeEventListener('touchstart', handleTouchStart);
        img.removeEventListener('touchmove', handleTouchMove);
        img.removeEventListener('touchend', handleTouchEnd);

        // Add listeners back
        img.addEventListener('dblclick', handleDblClick);
        img.addEventListener('wheel', handleWheel);
        img.addEventListener('mousedown', handleMouseDown);
        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);
        img.addEventListener('touchstart', handleTouchStart);
        img.addEventListener('touchmove', handleTouchMove);
        img.addEventListener('touchend', handleTouchEnd);
        
        // Double click to zoom
        img.addEventListener('dblclick', function(e) {
            console.log(e);
            e.preventDefault();
            if (zoomLevel > 1) {
                resetZoom();
            } else {
                zoomAtPoint(2, e.clientX, e.clientY);
            }
        });
        
        // Mouse wheel zoom
        img.addEventListener('wheel', function(e) {
            e.preventDefault();
            const delta = e.deltaY > 0 ? 0.9 : 1.1;
            let actualZoomLevel = zoomLevel * delta;
            if (actualZoomLevel < 1) actualZoomLevel = 1;
            if (actualZoomLevel > 3.3) actualZoomLevel = 3.3;;
            zoomAtPoint(actualZoomLevel, e.clientX, e.clientY);
        });
        
        // Mouse drag pan
        img.addEventListener('mousedown', function(e) {
            if (zoomLevel > 1) {
                e.preventDefault();
                isDragging = true;
                lastMouseX = e.clientX;
                lastMouseY = e.clientY;
                img.classList.add('dragging');
            }
        });
        
        document.addEventListener('mousemove', function(e) {
            if (isDragging && zoomLevel > 1) {
                const deltaX = e.clientX - lastMouseX;
                const deltaY = e.clientY - lastMouseY;
                
                panX += deltaX / zoomLevel;
                panY += deltaY / zoomLevel;
                
                constrainPan();
                updateImageTransform();
                
                lastMouseX = e.clientX;
                lastMouseY = e.clientY;
            }
        });
        
        document.addEventListener('mouseup', function() {
            if (isDragging) {
                isDragging = false;
                img.classList.remove('dragging');
            }
        });
        
        // Touch events for mobile
        let touchStartX = 0;
        let touchStartY = 0;
        let touchStartDistance = 0;
        
        img.addEventListener('touchstart', function(e) {
            if (e.touches.length === 1) {
                // Single touch - prepare for pan
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
                if (zoomLevel > 1) {
                    isDragging = true;
                    img.classList.add('dragging');
                }
            } else if (e.touches.length === 2) {
                // Two touches - prepare for pinch zoom
                e.preventDefault();
                const touch1 = e.touches[0];
                const touch2 = e.touches[1];
                touchStartDistance = Math.sqrt(
                    Math.pow(touch2.clientX - touch1.clientX, 2) + 
                    Math.pow(touch2.clientY - touch1.clientY, 2)
                );
                initialZoom = zoomLevel;
                isDragging = false;
            }
        });
        
        img.addEventListener('touchmove', function(e) {
            e.preventDefault();
            
            if (e.touches.length === 1 && isDragging && zoomLevel > 1) {
                // Single touch pan
                const deltaX = e.touches[0].clientX - touchStartX;
                const deltaY = e.touches[0].clientY - touchStartY;
                
                panX += deltaX / zoomLevel;
                panY += deltaY / zoomLevel;
                
                constrainPan();
                updateImageTransform();
                
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
            } else if (e.touches.length === 2) {
                // Two touches pinch zoom
                const touch1 = e.touches[0];
                const touch2 = e.touches[1];
                const currentDistance = Math.sqrt(
                    Math.pow(touch2.clientX - touch1.clientX, 2) + 
                    Math.pow(touch2.clientY - touch1.clientY, 2)
                );
                
                if (touchStartDistance > 0) {
                    const scale = currentDistance / touchStartDistance;
                    const newZoom = Math.max(1, Math.min(5, initialZoom * scale));
                    
                    if (newZoom !== zoomLevel) {
                        // Zoom at center point between touches
                        const centerX = (touch1.clientX + touch2.clientX) / 2;
                        const centerY = (touch1.clientY + touch2.clientY) / 2;
                        zoomAtPoint(newZoom, centerX, centerY);
                    }
                }
            }
        });
        
        img.addEventListener('touchend', function(e) {
            if (e.touches.length === 0) {
                isDragging = false;
                img.classList.remove('dragging');
            }
        });
    }

    // Initialize zoom and pan when modal is shown
    const originalShowModal = ShowModal;
    ShowModal = function() {
        originalShowModal();
        // Wait a bit for the image to load, then initialize zoom/pan
        setTimeout(initZoomPan, 100);
    };
    
</script>

</html>